<template>
	<view class="countdown-container" :style="containerStyle">
		<text class="countdown-number" :style="numberStyle">{{ remainingSeconds }}</text>
		<text class="countdown-unit" :style="unitStyle">{{unit}}</text>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		watch,
		defineProps,
		computed,
		defineEmits
	} from 'vue'

	const props = defineProps({
		initialSeconds: {
			type: Number,
			default: 180
		},
		unit:{
			type: String,
			default: 's'
		},
		numberSize: {
			type: String,
			default: '40rpx'
		}, // 数字大小
		numberColor: {
			type: String,
			default: '#ff4d4f'
		}, // 数字颜色
		numberWeight: {
			type: String,
			default: 'bold'
		}, // 数字粗细
		unitSize: {
			type: String,
			default: '24rpx'
		}, // 单位大小
		unitColor: {
			type: String,
			default: '#333'
		}, // 单位颜色
		containerBg: {
			type: String,
			default: ''
		}, // 容器背景
		borderRadius: {
			type: String,
			default: '0rpx'
		}, // 容器圆角
	})


	// 定义结束事件
	const emit = defineEmits(['finish'])

	// 剩余秒数（响应式）
	const remainingSeconds = ref(props.initialSeconds)
	// 定时器标识
	let timer = null
	// 计算样式对象
	const containerStyle = computed(() => ({
		backgroundColor: props.containerBg,
		borderRadius: props.borderRadius,
		padding: '0rpx 0rpx',
		display: 'flex',
		alignItems: 'center',
		justifyContent: 'center'
	}))

	const numberStyle = computed(() => ({
		fontSize: props.numberSize,
		color: props.numberColor,
		fontWeight: props.numberWeight,
		marginRight: '0rpx',
		lineHeight: ''
	}))

	const unitStyle = computed(() => ({
		fontSize: props.unitSize,
		color: props.unitColor,
		lineHeight: '1'
	}))
	// 开始倒计时
	const startCountdown = () => {
		// 清除已有定时器，避免重复计时
		if (timer) clearInterval(timer)

		// 每秒更新一次剩余时间
		timer = setInterval(() => {
			if (remainingSeconds.value > 0) {
				remainingSeconds.value--
			} else {
				// 倒计时结束
				clearInterval(timer)
				timer = null
				emit('finish') // 触发结束事件
			}
		}, 1000)
	}

	// 监听初始秒数变化（支持动态修改）
	watch(
		() => props.initialSeconds,
		(newVal) => {
			remainingSeconds.value = newVal // 更新剩余时间
			startCountdown() // 重新开始倒计时
		}, {
			immediate: true
		} // 初始加载时执行一次
	)

	// 组件卸载时清除定时器
	onUnmounted(() => {
		if (timer) {
			clearInterval(timer)
			timer = null
		}
	})
</script>

<style lang="scss">
	.countdown-container {
		// display: flex;
		// align-items: center;
		// justify-content: center;
		// padding: 15rpx 25rpx;
		// background-color: #f5f5f5;
		// border-radius: 8rpx;
	}

	.countdown-number {
		// font-size: 40rpx;
		line-height: 40rpx;
		// font-weight: bold;
		// color: #ff4d4f;
		/* 红色突出显示 */
		// line-height: 1;
		// margin-right: 5rpx;
	}

	// .countdown-unit {
	// 	font-size: 32rpx;
	// 	color: #333;
	// 	line-height: 1;
	// }
</style>